package my.test.memento.multistate;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.HashMap;

/**
 * @Author 许玉康
 * @Date 2019/9/29 13:55
 */
public class BeanUtils {

    //把bean的所有属性及数值放入到HashMap中
    public static HashMap<String, Object> backupProp(Object bean) {
        HashMap<String, Object> result = new HashMap<>();
        try {
            //获得Bean描述
            BeanInfo beanInfo = Introspector.getBeanInfo(bean.getClass());
            //获得属性的描述
            PropertyDescriptor[] descriptors = beanInfo.getPropertyDescriptors();
            //遍历所有的属性
            for(PropertyDescriptor descriptor:descriptors) {
                //属性名称
                String fileName = descriptor.getName();
                //读取属性的方法
                Method method = descriptor.getReadMethod();
                //读取属性值
                Object fieldValue = method.invoke(bean,new Object[]{});
                if(!fileName.equalsIgnoreCase("class")) {
                    System.out.println(fileName + "====" + fieldValue);
                    result.put(fileName, fieldValue);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return  result;
    }

    //把HashMap的值返回到bean中
    public static void restoreProp(Object bean, HashMap<String, Object> propMap) {
        try {
            //获得Bean描述
            BeanInfo beanInfo = Introspector.getBeanInfo(bean.getClass());
            //获得属性描述
            PropertyDescriptor[] descriptors = beanInfo.getPropertyDescriptors();
            //遍历所有的属性
            for (PropertyDescriptor descriptor : descriptors) {
                //属性名称
                String filedName = descriptor.getName();
                //如果有这个属性
                if(propMap.containsKey(filedName)) {
                    //写属性的方法
                    Method method = descriptor.getWriteMethod();
                    method.invoke(bean, new Object[]{propMap.get(filedName)});
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
